/**
 * author:ls
 * email:liusaint@gmail.com
 *
 */


var Mine = function (ele, faceele, panewidth, paneheight, minenum) {
    this.PANE_SIZE = 25;//每个格子的像素px大小。
    this.paneheight = paneheight;//有几行
    this.panewidth = panewidth;//有几列
    this.minenum = minenum;//有几个雷
    this.ele = document.getElementById(ele);
    this.cxt = this.ele.getContext("2d");
    this.faceele = document.getElementById(faceele);
};
Mine.prototype = {

    init: function () {

        var thats = this;
        $.get({
            async: true,
            url: "mines/mines_init",
            data: "row=" + this.paneheight + "&&col=" + this.panewidth + "&&num=" + this.minenum,
            success: function (text) {
                if (text === "success") {
                    //画格子
                    thats.ele.width = thats.PANE_SIZE * thats.panewidth;
                    thats.ele.height = thats.PANE_SIZE * thats.paneheight;
                    thats.faceele.src = "res/face_normal.bmp";
                    thats.createCells();//初始化cellArr数组,并涂上颜色。
                    thats.onclick();//点击方格事件
                    thats.preRightMenu();
                }
            }
        });

    },


    onclick: function () {
        var that = this;
        this.ele.onmouseup = function (e) {//点击事件。

            var pos = that.getCellPos(getEventPosition(e));

            if (e && e.button === 2) { //右键标记
                $.get({
                        async: true,
                        url: "mines/mines_flag",
                        data: "row=" + (pos[1] - 1) + "&&col=" + (pos[0] - 1),
                        success: function data(json) {
                            var point = json;
                            let row = point.row;
                            let col = point.col;
                            let flagged = point.flagged;
                            if (flagged) {
                                that.drawCell([col + 1, row + 1], 2); //如果为true
                            } else {
                                that.drawCell([col + 1, row + 1], 0);//否则为false
                            }
                        }
                    }
                );
            } else if (e.button === 0) { //左键点击
                $.get({
                    async: true,
                    url: "mines/mines_click",
                    data: "row=" + (pos[1] - 1) + "&&col=" + (pos[0] - 1),
                    success: function data(json) {
                        let state = json.state;
                        let lists = json.list;
                        if (state === 1) {
                            alert("胜利~~")
                        } else if (state === 2) {
                            alert("失败");
                        } else if (state === 3) {
                            var data = $.parseJSON(lists);
                            for (let point of data) {
                                let row = point.row;
                                let col = point.col;
                                let marked = point.marked;
                                let flagged = point.flagged;
                                if (!marked && !flagged) {
                                    that.drawCell([col + 1, row + 1], 1)
                                }
                            }

                            setTimeout(function () {
                                for (let point of data) {
                                    let row = point.row;
                                    let col = point.col;
                                    let marked = point.marked;
                                    if (!marked) {
                                        that.drawCell([col + 1, row + 1], 0)
                                    }
                                }

                            }, 100);

                            return;
                        }
                        var parseJSON = $.parseJSON(lists);
                        for (let point of parseJSON) {
                            let row = point.row;
                            let col = point.col;
                            let value = point.value;
                            let flagged = point.flagged;
                            if (value >= 0 && value < 9) {
                                if (flagged) {
                                    that.drawCell([col + 1, row + 1], 6);
                                } else {
                                    that.drawNum([col + 1, row + 1], value);
                                }
                            } else if (value === 9) { //如果为雷,点中雷
                                if (row === pos[1] - 1 && col === pos[0] - 1) {
                                    that.drawCell([col + 1, row + 1], 5);
                                } else {  //正常雷
                                    if (flagged) {
                                        that.drawCell([col + 1, row + 1], 2);
                                    } else {
                                        that.drawCell([col + 1, row + 1], 4);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
    },

    createCells: function () {//初始化cellArr，保存每个格子的状态。
        var paneheight = this.paneheight;
        var panewidth = this.panewidth;
        for (var i = 0; i < panewidth; i++) {
            for (var j = 0; j < paneheight; j++) {
                this.drawCell([i + 1, j + 1], 0);
            }
        }
    },

    drawCell: function (pos, type) {//绘制不同种类的格子。
        var area = this.getCellArea(pos);
        var cxt = this.cxt;
        var image = new Image();
        var srcArr = ["res/blank.bmp", "res/0.bmp", "res/flag.png", "res/ask.bmp", "res/mine.png", "res/boom.png", "res/error.png"];
        image.src = srcArr[type];
        image.onload = function () {
            cxt.drawImage(image, area[0], area[1], 25, 25);
        }
    }
    ,
    drawNum: function (pos, num) {//绘制数字 0-8
        var area = this.getCellArea(pos);
        var cxt = this.cxt;
        var image = new Image();
        image.src = "res/" + num + ".bmp";
        image.onload = function () {
            cxt.drawImage(image, area[0], area[1], 25, 25);
        }
    }
    ,
    getCellArea: function (pos) {//根据格子坐标返回一个格子左上角的像素坐标[32,666];
        return [(pos[0] - 1) * this.PANE_SIZE + 1, (pos[1] - 1) * this.PANE_SIZE + 1];
    }
    ,
    getCellPos: function (coordinate) {//根据像素坐标返回格子坐标。[3,5];
        return [Math.ceil(coordinate.x / this.PANE_SIZE), Math.ceil(coordinate.y / this.PANE_SIZE)];
    }
    ,
    preRightMenu: function () {//阻止右键菜单
        this.ele.oncontextmenu = function (event) {
            if (document.all) window.event.returnValue = false;// for IE
            else event.preventDefault();
        }
    }
}
;

//获取坐标：解决canvas在高分屏缩放150%之后坐标计算不准确的问题。
//https://github.com/zbinlin/blog/blob/master/getting-mouse-position-in-canvas.md
function getEventPosition(evt) {
    var x, y;
    var x = evt.clientX;
    var y = evt.clientY;
    var rect = document.getElementById('mine1').getBoundingClientRect();
    x -= rect.left;
    y -= rect.top;
    return {x: x, y: y};
}

